<?php
namespace Model;

use Illuminate\Database\Capsule\Manager as DB;
use Library\Log;


/**
 * Base Model
 * @author los_gsy
 */
class Base {
	/**
	 * test
	 * @return string
	 */
	static public function test() {
		return __METHOD__;
	}


	/**
	 * 新增一条记录
	 * @param array $data
	 * @return int 新增记录行的id
	 */
	static public function add($data) {
		$result = DB::table(self::getTableName())
			->insertGetId($data);
		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 批量新增记录行
	 * @param array $data
	 */
	static public function addList($data) {
		foreach ($data as $row) {
			$result = self::add($row);
			if (!$result) {
				Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
			}
		}
	}


	/**
	 * 删除一条记录，根据id
	 * @param int $id
	 * @return int 影响的行数
	 */
	static public function del($id) {
		$result = DB::table(self::getTableName())
			->where('id', $id)
			->delete();
		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 批量删除记录，根据id列表
	 * @param array $id_list
	 * @return int 影响的行数
	 */
	static public function delList($id_list) {
		$result = DB::table(self::getTableName())
			->whereIn('id', $id_list)
			->delete();
		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 更新一条记录，根据id
	 * @param int $id
	 * @param array $data
	 * @return int 影响的行数
	 */
	static public function update($id, $data) {
		$result = DB::table(self::getTableName())
			->where('id', $id)
			->update($data);

		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 查询一条记录，根据id
	 * @param int $id
	 * @return null|object
	 */
	static public function get($id) {
		$result = DB::table(self::getTableName())
			->where('id', $id)
			->first();
		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 查询记录列表，根据id列表
	 * @param array $id_list
	 * @return array
	 */
	static public function getList($id_list) {
		$result = DB::table(self::getTableName())
			->whereIn('id', $id_list)
			->get();
		if (!$result) {
			Log::error(__METHOD__ . ': $result = ' . var_export($result, true));
		}
		return $result;
	}


	/**
	 * 获取表名
	 * @return string
	 */
	static public function getTableName() {
		$full_class_name = get_called_class();
		$class_name = substr($full_class_name, strrpos($full_class_name, '\\') + 1);
		return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $class_name));
	}



}